﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GabageFactory.Models;

namespace GabageFactory.Controllers
{
    [HandleError]
    public class BaseController : Controller
    {
        //
        // GET: /Base/

        protected ActionResult AllowForRole(RoleEnum role)
        {
            if (!FormsAuthenticationService.IsInRole(role))
            {
                return RedirectToAction("Deny", "Home");
            }

            return null;
        }

        protected User GetCurrentUser()
        {
            return FormsAuthenticationService.GetCurrentUser();
        }

        protected void ShowFactoryList(long factoryId)
        {
            FactoryReposity factoryReposity = new FactoryReposity();
            List<SelectListItem> factories = new List<SelectListItem>();
            foreach (Factory f in factoryReposity.ListFactories())
            {
                bool selected = false;
                if (factoryId == f.Id)
                {
                    selected = true;
                }
                factories.Add(new SelectListItem { Text = f.Name, Value = f.Id.ToString(), Selected = selected });
            }
            ViewData["factories"] = factories;
        }

        protected void ShowRoleList(long roleId)
        {
            RoleReposity roleReposity = new RoleReposity();
            List<SelectListItem> roles = new List<SelectListItem>();
            foreach (Role r in roleReposity.ListRoles())
            {
                bool selected = false;
                if (roleId == r.Id)
                {
                    selected = true;
                }
                roles.Add(new SelectListItem { Text = r.Name, Value = r.Id.ToString(), Selected = selected });
            }
            ViewData["roles"] = roles;
        }

        protected void ShowFactoryAndRoleList(User user)
        {
            long factoryId = 0, roleId = 0;
            if (user != null)
            {
                factoryId = user.FactoryId;
                roleId = user.RoleId;
            }
            ShowFactoryList(factoryId);
            ShowRoleList(roleId);
        }


        protected int parseInt(string value)
        {
            int result = 0;
            try
            {
                result = int.Parse(value);
            }
            catch
            {
                // empty
            }

            return result;
        }

        protected float parseFloat(string value)
        {
            float result = 0;
            try
            {
                result = float.Parse(value);
            }
            catch
            {
                // empty
            }

            return result;
        }

    }
}
